﻿using Canon;
using EDSDKLib;
using Karbel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace ConfExpert.EOS
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        #region Barcode
        public delegate void BarcodeReadHandler(int Barcode);
        public event BarcodeReadHandler BarcodeRead;
        public void FireBarcodeRead(int Barcode)
        {
            if (BarcodeRead != null)
                BarcodeRead(Barcode);
        }
        void portBarcodeScanner_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string data = portBarcodeScanner.ReadExisting();

            if (data.EndsWith("\r\n"))
            {
                data = data.Replace("\r\n", "");

                //son hane parity ve tip alanları atılınca geri kalan çıplak barkod
                int barcode = int.Parse(data.Substring(0, data.Length - 1));

                FireBarcodeRead(barcode);
            }
        }
        #endregion

        SDKHandler CameraHandler;


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseSession();
            CameraHandler.Dispose();
        }

        void CameraHandler_CameraHasShutdown(object sender, EventArgs e)
        {
            CloseSession();
        }

        private void CloseSession()
        {
            CameraHandler.CloseSession();
        }

        DataManager DataManager;
        string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Photos";

        TextBox t = new TextBox();
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Controls.Add(t);
            t.Width = 10;
            t.TextChanged += t_TextChanged;
            //this.Visible = false;
            this.Shown += MainForm_Shown;
            btn.Click += btn_Click;
            textEdit1.KeyPress += textEdit1_KeyPress;
            this.FormClosing += MainForm_FormClosing;
            //this.KeyDown += MainForm_KeyDown;

            using (Login login = new Login())
            {
                DialogResult dr = login.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    this.Visible = true;

                    DataManager = new DataManager(login.ConnectionString);
                    InitCamera();
                    InitBarcode();
                }
                else
                    Application.Exit();
            }
        }

        void textEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter) ||
                e.KeyChar == Convert.ToChar(Keys.Return))
            {
                this.Text = textEdit1.Text;
                textEdit1.Text = string.Empty;
                MainForm_BarcodeRead(int.Parse(this.Text) / 10);

            }
        }

        string Folder = @"D:\AksPhoto\";
        void btn_Click(object sender, EventArgs e)
        {
            MainForm_BarcodeRead(0);
            t.Focus();

            /*
            DirectoryInfo di = new DirectoryInfo(Folder);

            foreach (FileInfo fi in di.GetFiles())
            {
                //fi.Delete();

                path = fi.FullName;
                string pathT = path.Replace(".JPG", "-unsharpened.JPG");
                KalikoImage sharpimg = new KalikoImage(path).GetThumbnailImage(1068, 710, ThumbnailMethod.Fit);     //427,284
                sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2, 0.4));
                sharpimg.SaveJpg(pathT, 95);

                byte[] bytes = File.ReadAllBytes(path);
                byte[] bytesT = File.ReadAllBytes(pathT);

                //burada biriken resimlere photoshop'ta auto contrast + smart sharpen uygula
                //ek bir programla klasörde biriken resimleri tek tek veritabanına kaydet!

                Code = int.Parse(fi.Name.Replace(".JPG", string.Empty));
                string ret = DataManager.ExecuteScalar("UpdAksPhoto", "S", Code, bytes, bytesT).ToString();
                //labelControl1.Invoke((MethodInvoker)(() => labelControl1.Text = ret));
                File.Copy(path, +Code + ".JPG", true);
            }
             */
        }

        void t_TextChanged(object sender, EventArgs e)
        {
            if (t.Text.Length >= 8)
            {
                this.Text = t.Text;
                t.Text = string.Empty;
                MainForm_BarcodeRead(int.Parse(this.Text) / 10);
            }
        }

        void MainForm_Shown(object sender, EventArgs e)
        {
            t.Focus();
        }



        //void MainForm_KeyDown(object sender, KeyEventArgs e)
        //{
        //    if (e.KeyCode == Keys.F1)
        //    {
        //        if (wait)
        //            Kaydet(fl);
        //        else
        //        {
        //            Code = 1703;
        //            pictureBox1.Image = null;
        //            CameraHandler.TakePhoto();
        //        }

        //        wait = false;
        //    }
        //}

        private void InitBarcode()
        {
            portBarcodeScanner = new System.IO.Ports.SerialPort(Properties.Settings.Default.BarcodeComPort);
            portBarcodeScanner.BaudRate = 57600;
            portBarcodeScanner.DataBits = 8;
            portBarcodeScanner.Parity = System.IO.Ports.Parity.Mark;
            portBarcodeScanner.StopBits = System.IO.Ports.StopBits.One;
            portBarcodeScanner.DtrEnable = true;
            //portBarcodeScanner.Open();
            //portBarcodeScanner.DataReceived += portBarcodeScanner_DataReceived;
            BarcodeRead += MainForm_BarcodeRead;
        }

        private void InitCamera()
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            else
            {
                DirectoryInfo di = new DirectoryInfo(path);
                /*
                foreach (FileInfo fi in di.GetFiles())
                    fi.Delete();
                 */
            }

            CameraHandler = new SDKHandler();
            CameraHandler.DownloadCompleted += CameraHandler_DownloadCompleted;
            CameraHandler.CameraHasShutdown += CameraHandler_CameraHasShutdown;
            CameraHandler.ImageSaveDirectory = path;

            List<Camera> CamList = CameraHandler.GetCameraList();

            if (CamList.Count > 0)
            {
                Camera camera = CamList[0];
                this.Text = camera.Info.szDeviceDescription;
                CameraHandler.OpenSession(camera);

                CameraHandler.SetSetting(EDSDK.PropID_SaveTo, (uint)EDSDK.EdsSaveTo.Host);
                CameraHandler.SetCapacity();
            }
        }

        void CameraHandler_DownloadCompleted(string path)
        {
            fl = path;
            this.Text = Code.ToString();
            Image bmp = Bitmap.FromFile(path);
            //pictureBox1.Image = bmp.CropFromCenter(500); 
            pictureBox1.Image = bmp;

            if (Code > 0)
                Kaydet(path);
            else
                labelControl1.Text = "Beklemede...";
        }

        private void Kaydet(string path)
        {
            //string pathT = path.Replace(".JPG", "-unsharpened.JPG");
            //KalikoImage sharpimg = new KalikoImage(path).GetThumbnailImage(1068, 710, ThumbnailMethod.Fit);     //427,284
            //sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2, 0.4));
            //sharpimg.SaveJpg(pathT, 95);

            
            byte[] bytes = File.ReadAllBytes(path);
            //byte[] bytesT = File.ReadAllBytes(pathT);


            //if (File.Exists(path))
                File.Copy(path, Folder + Code + ".JPG", true);

            GC.Collect();

            //burada biriken resimlere photoshop'ta auto contrast + smart sharpen uygula
            //ek bir programla klasörde biriken resimleri tek tek veritabanına kaydet!

            DirectoryInfo di = new DirectoryInfo(Folder);
            labelControl1.Invoke((MethodInvoker)(() => labelControl1.Text = di.GetFiles().Length.ToString()));

            //string ret = DataManager.ExecuteScalar("UpdAksPhoto", "S", Code, bytes, bytesT).ToString();
            //labelControl1.Invoke((MethodInvoker)(() => labelControl1.Text = ret));
            Code = 0;
        }

        string fl;
        int Code = 0;
        bool wait = false;
        void MainForm_BarcodeRead(int Barcode)
        {
            Code = Barcode;

            if (wait && Barcode > 0)
                Kaydet(fl);
            else
            {
                pictureBox1.Image = null;

                CameraHandler.TakePhoto();
            }

            wait = Barcode == 0;

        }

        /*
        void Kaiko()
        {
            KalikoImage image = new KalikoImage(@"E:\IMG_0001.JPG");
            image.BackgroundColor = Color.Aquamarine;

            image.GetThumbnailImage(427, 284, ThumbnailMethod.Fit).SaveJpg(@"E:\thumbnail-fit.jpg", 95);

            //image.GetThumbnailImage(100, 140, ThumbnailMethod.Crop).SaveJpg("thumbnail-crop.jpg", 90);

            //image.GetThumbnailImage(100, 140, ThumbnailMethod.Pad).SaveJpg("thumbnail-pad.jpg", 90);

            KalikoImage sharpimg = image.GetThumbnailImage(427, 284, ThumbnailMethod.Fit);  // image.GetThumbnailImage(100, 100, ThumbnailMethod.Crop);
            sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2, 0.3));
            sharpimg.SaveJpg(@"E:\thumbnail-unsharpened.jpg", 95);

            // Apply unsharpen filter (radius = 1.4, amount = 32%)
            //sharpimg.ApplyFilter(new UnsharpMaskFilter(1.4, 0.32));


            sharpimg.ApplyFilter(new DesaturationFilter());
            sharpimg.SaveJpg(@"E:\thumbnail-gray.jpg", 90);

            sharpimg.ApplyFilter(new ContrastFilter(30));
            sharpimg.SaveJpg(@"E:\thumbnail-contrast.jpg", 90);


        }
         */

        private uint downloadImage(IntPtr directoryItem)
        {
            uint error = EDSDK.EDS_ERR_OK;
            IntPtr stream = IntPtr.Zero;

            EDSDK.EdsDirectoryItemInfo directoryItemInfo;

            error = EDSDK.EdsGetDirectoryItemInfo(directoryItem, out directoryItemInfo);

            //create a file stream to accept the image
            if (error == EDSDK.EDS_ERR_OK)
                error = EDSDK.EdsCreateMemoryStream(directoryItemInfo.Size, out stream);

            //download image
            if (error == EDSDK.EDS_ERR_OK)
                error = EDSDK.EdsDownload(directoryItem, directoryItemInfo.Size, stream);

            //complete download
            if (error == EDSDK.EDS_ERR_OK)
                error = EDSDK.EdsDownloadComplete(directoryItem);


            //convert to memory stream
            IntPtr pointer; //pointer to image stream
            EDSDK.EdsGetPointer(stream, out pointer);

            uint length = 0;
            EDSDK.EdsGetLength(stream, out length);

            byte[] bytes = new byte[length];

            //Move from unmanaged to managed code.
            Marshal.Copy(pointer, bytes, 0, bytes.Length);

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(bytes);
            Image image = System.Drawing.Image.FromStream(memoryStream);

            if (pointer != IntPtr.Zero)
            {
                EDSDK.EdsRelease(pointer);
                pointer = IntPtr.Zero;
            }

            if (directoryItem != IntPtr.Zero)
            {
                EDSDK.EdsRelease(directoryItem);
                directoryItem = IntPtr.Zero;
            }

            if (stream != IntPtr.Zero)
            {
                EDSDK.EdsRelease(stream);
                stream = IntPtr.Zero;
            }

            return error;
        }
    }
}

